﻿using Newtonsoft.Json.Linq;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using static System.Net.Mime.MediaTypeNames;

namespace TVBox源合并工具
{
    public class HttpHelper
    {
        public static string HttpGet(string url)
        {
            string result = "";
            using (var client = new HttpClient())
            {
                var response = client.GetAsync(url).Result;
                result = response.Content.ReadAsStringAsync().Result;
            }

            return result;
        }

        public static bool HttpDownload(string url, string filename)
        {
            using (WebClient client = new WebClient())
            {
                client.DownloadFile(url, filename);
            }
            return true;
        }

        public static bool HttpGetSource(string url, string filename)
        {
            try
            {
                url = GetSiteByChn(url);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";

                request.ContentType = "text/html;charset=UTF-8";
                request.UserAgent = "okhttp/3.15";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);

                string content = myStreamReader.ReadToEnd();

                myStreamReader.Close();
                myResponseStream.Close();

                if (!IsJson(content))
                {
                    //Base64解码
                    Regex regex = new Regex("[A-Za-z0]{8}\\*\\*");
                    MatchCollection matches = regex.Matches(content);

                    if (matches.Count > 0)
                    {
                        content = content.Substring(content.IndexOf(matches[0].Value) + 10);
                        content = Encoding.UTF8.GetString(Convert.FromBase64String(content));
                    }

                    if (content.StartsWith("2423"))
                    {
                        string data = content.Substring(content.IndexOf("2324") + 4, content.Length - 26 - (content.IndexOf("2324") + 4));

                        byte[] byteArray = ToBytes(content);
                        content = Encoding.UTF8.GetString(byteArray).ToLower();

                        string key = RightPadding(content.Substring(content.IndexOf("$#") + 2, content.IndexOf("#$") - (content.IndexOf("$#") + 2)), "0", 16);
                        string iv = RightPadding(content.Substring(content.Length - 13), "0", 16);

                        content = CBC(data, key, iv);
                    }
                }
                File.WriteAllText(filename, content);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 校验字符串是否Json格式
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static bool IsJson(string json)
        {
            try
            {
                JToken.Parse(json);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 中文站点转换
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetSiteByChn(string url)
        {
            bool hasChn = Regex.IsMatch(url, @"[\u4e00-\u9fa5]");

            if (hasChn)
            {
                string chineseDomain = "";
                string http = "";
                if (url.Substring(0, 7) == "http://")
                {
                    http = "http://";
                    chineseDomain = url.Substring(7);
                }
                else if (url.Substring(0, 8) == "https://")
                {
                    http = "https://";
                    chineseDomain = url.Substring(8);
                }

                string punycodeDomain = new System.Globalization.IdnMapping().GetAscii(chineseDomain);
                return http + punycodeDomain;
            }
            else
            {
                return url;
            }
        }

        public static byte[] ToBytes(string src)
        {
            int l = src.Length / 2;
            byte[] ret = new byte[l];

            for (int i = 0; i < l; i++)
            {
                string subStr = src.Substring(i * 2, 2);
                ret[i] = Convert.ToByte(int.Parse(subStr, System.Globalization.NumberStyles.HexNumber));
            }

            return ret;
        }

        public static string CBC(string data, string key, string iv)
        {
            try
            {
                using (AesManaged aes = new AesManaged())
                {
                    aes.Mode = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;

                    aes.Key = Encoding.UTF8.GetBytes(key);
                    aes.IV = Encoding.UTF8.GetBytes(iv);

                    ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                    byte[] encryptedBytes = ToBytes(data);
                    byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);

                    return Encoding.UTF8.GetString(decryptedBytes);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            return null;
        }

        static string ECB(string data, string key)
        {
            try
            {
                key = RightPadding(key, "0", 16); // 调用右侧填充方法，确保密钥长度为16字节
                byte[] encryptedBytes = ToBytes(data); // 将待解密数据转换为字节数组
                byte[] keyBytes = Encoding.UTF8.GetBytes(key); // 将密钥转换为字节数组

                using (AesManaged aes = new AesManaged())
                {
                    aes.Mode = CipherMode.ECB; // 设置加密模式为ECB
                    aes.Padding = PaddingMode.PKCS7; // 设置填充模式为PKCS7Padding
                    aes.Key = keyBytes; // 设置密钥

                    ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); // 创建解密器

                    byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); // 解密数据

                    return Encoding.UTF8.GetString(decryptedBytes); // 返回解密后的字符串结果
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            return null;
        }

        static string RightPadding(string key, string replace, int length)
        {
            string strReturn = "";
            int curLength = key.Trim().Length;

            if (key != null && curLength > length)
            {
                strReturn = key.Trim().Substring(0, length);
            }
            else if (key != null && curLength == length)
            {
                strReturn = key.Trim();
            }
            else
            {
                int diff = length - curLength;
                StringBuilder stringBuilder = new StringBuilder(key.Trim());

                for (int i = 0; i < diff; i++)
                {
                    stringBuilder.Append(replace);
                }

                strReturn = stringBuilder.ToString();
            }

            return strReturn;
        }
    }
}
